<template>
  <view class="settings">
    <view class="settings-content">
      <view class="section-box">
        <view class="section-content">
          <view class="item-line">
            <view class="line-field">
              <view class="label">
                <text>场景名称</text>
              </view>
              <view class="operate">
                <input :disabled="!enableEdit" placeholder="请输入场景名称" v-model="sceneName" maxlength="10" />
              </view>
            </view>
          </view>
          <view class="item-line">
            <view class="line-field">
              <view class="label">
                <text>选择段式</text>
              </view>
              <view class="operate">
                <uni-data-checkbox :disabled="!enableEdit" v-model="sceneType" :localdata="sceneTypeList" :selectedColor="color.primary"></uni-data-checkbox>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view class="section-box">
        <view class="section-title"><view class="title">灯具参数</view></view>
        <view class="section-content">
          <view class="item-line" v-for="item in paramList" :key="item.key" v-show="!item.hidden">
            <template v-if="item.type === FIELD_TYPE.NUMBER">
              <view class="line-field">
                <view class="label">
                  <text>{{item.label}}</text>
                </view>
                <view class="operate">
                  <uni-number-box :disabled="!enableEdit" :min="item.min" :max="item.max" v-model="item.value" :step="item.step" />
                </view>
              </view>
              <view class="line-desc" v-if="!!item.desc">{{ item.desc }}</view>
            </template>
            <template v-if="item.type === FIELD_TYPE.INPUT">
              <view class="line-field">
                <view class="label">
                  <text>{{item.label}}</text>
                </view>
                <view class="operate">
                  <input :disabled="!enableEdit" placeholder="请输入" v-model="item.value" />
                </view>
              </view>
              <view class="line-desc" v-if="item.desc"></view>
            </template>
            <template v-if="item.type === FIELD_TYPE.SWITCH">
              <view class="line-field">
                <view class="label">
                  <text>{{item.label}}</text>
                </view>
                <view class="operate">
                  <switch :disabled="!enableEdit" :checked="!!item.value" @change="switchToggle(item)" />
                </view>
              </view>
              <view class="line-desc" v-if="item.desc"></view>
            </template>
            <template v-if="item.type === FIELD_TYPE.SELECT">
              <view class="line-field">
                <view class="label">
                  <text>{{item.label}}</text>
                </view>
                <view class="operate">
                  <view v-if="!enableEdit" class="disabled-layer" @click.prevent></view>
                  <uni-data-select
                      v-model="item.value"
                      :localdata="item.range"
                      :clear="false"
                  ></uni-data-select>
                </view>
              </view>
              <view class="line-desc" v-if="item.desc"></view>
            </template>
          </view>
        </view>
      </view>
    </view>
    <view v-show="enableEdit" class="page-bottom-btn" @click="saveSetting()">确定</view>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { FIELD_TYPE, USER_ROLE } from '@/constant/index.js'
import { getGUID } from '@/utils/index.js'
import color from '@/envs/_/variables.scss'
export default {
  mixins: [mixin],
  data() {
    return {
      FIELD_TYPE,
      sceneName: '',
      paramList: [],
      paramMap: {},
      typeThreeFields: [],
      currentParam: {},
      sceneTypeList: [
        { text: '二段式', value: 2 },
        { text: "三段式", value: 3 },
      ],
      sceneType: 2,
      color,
      readonly: true,
      enableEdit: false
    }
  },
  mounted() {
    if (this.params.sceneId) {
      this.getScenarioDetail()
    } else {
      this.readonly = false
      this.enableEdit = true
      uni.setNavigationBarTitle({
        title: '新增场景'
      })
      this.getParamList()
    }
  },
  watch: {
    sceneType() {
      this.typeThreeFields.forEach((item) => {
        item.hidden = this.sceneType === 2;
      });
    }
  },
  methods: {
    getScenarioDetail() {
      const self = this
      uni.request({
        url: '/project_scene/get',
        method: 'GET',
        data: {
          id: this.params.sceneId,
        },
        success(result) {
          if (result.data.success && result.data.data) {
            self.sceneName = result.data.data.name || ''
            self.sceneType = result.data.data.type
            self.readonly = result.data.data.xm_id === 0
            self.enableEdit = !self.readonly && self.params.canEdit === 'true'
            uni.setNavigationBarTitle({
              title: self.enableEdit ? '编辑场景' : '查看场景'
            })
            if (result.data.data.param) {
              try {
                self.currentParam = JSON.parse(result.data.data.param)
              } catch (e) {
                self.currentParam = {}
                console.error('JSON parse error', e)
              }
            }
            self.getParamList()
          }
        },
        complete() {
          uni.stopPullDownRefresh()
        }
      })
    },

    getParamList() {
      const self = this
      self.paramMap = {}
      self.paramList = []
      self.typeThreeFields = []
      uni.request({
        url: '/sys/fieldsn',
        method: 'GET',
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach((item) => {
              if (!item) return
              const { label = '', name, value, type, step = 1, min = 0, max = 100, desc, range = [], user = 1 } = item
              range.forEach((option) => {
                option.text = option.name || ''
              })
              const paramItem = {
                key: getGUID(),
                label,
                name,
                value: self.currentParam[name] ?? value,
                type,
                step,
                min,
                max,
                desc,
                range,
                hidden: user === 1 ? false : self.userInfo.role !== USER_ROLE.ADMIN
              }
              paramItem.range.forEach((option) => {
                option.text = option.name || '';
              });
              self.paramMap[name] = paramItem;
              arr.push(paramItem)
              if (name === 'middle_light') {
                paramItem.hidden = self.sceneType === 2;
                self.typeThreeFields.push(paramItem);
              }
            })
            self.paramList = arr
          }
        }
      })
    },
    switchToggle(target) {
      target.value = !target.value
    },
    checkCanSubmit() {
      const self = this
      self.sceneName = `${self.sceneName}`.trim()
      if (!self.sceneName) {
        uni.showToast({
          icon: 'none',
          title: '请输入场景名称'
        })
        return false
      }
      return true
    },
    saveSetting() {
      const self = this
      if (!self.checkCanSubmit()) return
      let url = '/project_scene/add'
      const data = {
        xm_id: self.params.projectId,
        name: self.sceneName,
        type: self.sceneType
      }
      if (self.params.sceneId) {
        url = '/project_scene/modify'
        data.id = self.params.sceneId
      }
      const param = {}
      self.paramList.forEach((item) => {
        param[item.name] = item.value
        if (typeof item.value === 'boolean') {
          param[item.name] = +item.value
        }
      })
      data.param = JSON.stringify(param)
      uni.request({
        url,
        method: 'GET',
        data,
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'none',
              title: '保存成功'
            })
            self.goBack()
          }
        }
      })
    },
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style scoped lang="scss">
.settings {
  padding: 20rpx 30rpx 120rpx;
}
.section-box {
  padding: 30rpx;
  background-color: $white;
  border-radius: 10rpx;
  margin-top: 40rpx;
  &:first-child {
    margin-top: 0;
  }
}
.section-title {
  @include section-title;
  & + .section-content {
    margin-top: 30rpx;
  }
}
.item-line {
  margin-top: 30rpx;
  &:first-child {
    margin-top: 0;
  }
  .line-field {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .operate {
      position: relative;
      text-align: right;
      input {
        font-size: 28rpx;
      }
    }
  }
  .operate-btn {
    padding: 0 30rpx;
    border: 2rpx solid $primary;
    border-radius: 6rpx;
    color: $primary;
    margin-left: 20rpx;
    &:first-child {
      margin-left: 0;
    }
  }
  .line-desc {
    font-size: $font-size-0;
    color: $text-secondary;
  }
  .label {
    font-size: $font-size-3;
    vertical-align: baseline;
    .info {
      font-size: $font-size-0;
      color: $text-secondary;
    }
  }
}
.item-operate {
  margin-top: 40rpx;
  .operate-label {
    font-size: $font-size-3;
    font-weight: bold;
  }
  .line-desc {
    font-size: $font-size-0;
    color: $text-secondary;
  }
  .btn-box {
    margin-top: 10rpx;
    display: flex;
    flex-wrap: wrap;
    .operate-btn {
      font-size: $font-size-2;
      border-radius: 8rpx;
      height: 56rpx;
      display: flex;
      align-items: center;
      margin-right: 30rpx;
      padding: 0 30rpx;
      border: 2rpx solid $primary;
      color: $primary;
    }
  }
}
</style>
